//
//  QuickScanCollectionView.m
//  FKGW
//
//  Created by song ce on 2017/2/18.
//  Copyright © 2017年 song ce. All rights reserved.
//

#import "QuickScanCollectionView.h"
#import "BaseNavigationViewController.h"
#import "UIView+Extend.h"
#import "GoodsDetailViewController.h"
#import "LoginViewController.h"
#import "OSSHelper.h"
@implementation QuickScanCollectionView

-(void)setCount:(NSInteger)count{
    _count = count;
}
- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if(self){
        self.dataSoure = [NSMutableArray array];
        //本地路径。创建文件夹
        NSString *path=[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/QuickScanPhotos"];
        BOOL is= [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:NO attributes:nil error:nil];
        if(is){
            DLog(@"目录创建成功 ");
        }else{
            DLog(@"目录已存在 ");
        }

        self.currentPage = 0;
        self.backgroundColor = [UIColor blackColor];
        [self _initSubviews];
        //点击删除按钮删除一张图片
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(deleteOnePhoto) name:@"deleteOnePhoto" object:nil];
        //加载更多完毕通知
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(ScanAllLoadMoreData) name:@"ScanAllLoadMoreData" object:nil];
          }
    return self;
}

-(void)ScanAllLoadMoreData{
    self.isLoadMoreData = YES;
}
//点击删除按钮删除一张图片
-(void)deleteOnePhoto{
    if(self.dataSoure.count==1){
        [MBProgressHUD showTipMessageInWindow:@"最后一张"];
        if(self.lastOnePhotoBlock){
            self.lastOnePhotoBlock();
        }
        return;
    }else if(self.dataSoure.count>1){
        [_dataSoure removeObjectAtIndex:self.currentPage];
        [_myCollectionView reloadData];
    }
    if(self.currentPage>=self.dataSoure.count){
        self.currentPage=(int)self.dataSoure.count-1;
    }
    //删除图片后更新控制器中的数据源
    if(self.updataDataSourceBlock){
        self.updataDataSourceBlock(self.dataSoure);
    }
    //删除一张后刷新界面并显示滚动到相应 的位置显示下张图片 如果删除的是最后一张显示前一张图片
    NSIndexPath *lastIndexPath=[NSIndexPath indexPathForRow:self.currentPage inSection:0];
    [_myCollectionView  scrollToItemAtIndexPath:lastIndexPath atScrollPosition:UICollectionViewScrollPositionTop animated:NO];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"currentPage" object:[NSString stringWithFormat:@"%d",self.currentPage]];
}
-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

//从QuickScanViewController中传来的数据源
-(void)setDataArr:(NSMutableArray *)dataArr{
    _dataArr = dataArr;
    if(dataArr.count==0){
        [MBProgressHUD showTipMessageInWindow:@"没有了"];
        if(!self.isLoadMoreData){
            if(self.noPicsBlock){
                self.noPicsBlock();
            }
        }
        [self.indicatorView removeFromSuperview];
        __weak typeof(self) weakSelf = self;
        [UIView animateWithDuration:.5 animations:^{
            weakSelf.myCollectionView.left = 0;
            if(weakSelf.dataSoure.count){
                 NSIndexPath *indexPath=[NSIndexPath indexPathForRow:weakSelf.currentPage inSection:0];
                 [weakSelf.myCollectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
            }
        }];
        return;
    }
    if(!self.isWriteToLocal){
        [self loadIamge];
    }else{
        [_myCollectionView reloadData];
    }
}

//加载图片
-(void)loadIamge{
    self.isWriteToLocal = YES;
    __weak typeof(self) weakSelf = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        for(int i = 0;i<_dataArr.count;i++){
            QickScanModel *item = _dataArr[i];
            //测试
//            NSString *linshi = [NSString stringWithFormat:@"user/header/%@%@",USERID,@".jpeg"];
            [[OSSHelper sharedHelper] OSSDownLoadWithObjectKey:item.pic downLoadBlock:^(NSData *data) {
                //保存到本地
                [weakSelf saveTolocal:data index:i];
            }];
        }
    });
 }

-(void)saveTolocal:(NSData*)imageData index:(int)index{
    NSString *imageName ;
    UIImage *image= [UIImage imageWithData:imageData];
    if(UIImagePNGRepresentation(image)){//返回为png图像
        imageName = [NSString stringWithFormat:@"%@.png",[self getTimeNow]];
    }else{ //返回为JPEG图像
        imageName = [NSString stringWithFormat:@"%@.jpg",[self getTimeNow]];
    }
    //本地路径
    NSString *path=[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/QuickScanPhotos"];
    //创建文件
    path = [path stringByAppendingString:[NSString stringWithFormat:@"/%@",imageName]];
    BOOL isSuccess= [[NSFileManager defaultManager] createFileAtPath:path contents:imageData attributes:nil];
    if(!isSuccess){
        NSLog(@"失败");
    }
    DLog(@"path---%@",path);
    if(isSuccess){
        //回到主线城刷新UI
        dispatch_async(dispatch_get_main_queue(), ^{
            QickScanModel *item = _dataArr[index];
            item.pic = path;
            if(index==self.dataArr.count-1){
                [self.dataSoure addObjectsFromArray:self.dataArr];
                  [_myCollectionView reloadData];
                if(self.isLoadMoreData){//加载更多刷新完毕--店铺内加载更多
                    [self.indicatorView removeFromSuperview];
                    __weak typeof(self) weakSelf = self;
                    [UIView animateWithDuration:.5 animations:^{
                            weakSelf.myCollectionView.left = 0;
                        NSIndexPath *indexPath=[NSIndexPath indexPathForRow:weakSelf.currentPage inSection:0];
                        [weakSelf.myCollectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
                    }];
                }
                _myCollectionView.hidden = NO;
                self.isWriteToLocal = NO;
                DLog(@"----****-----%zd",self.dataSoure.count);
                //更新控制器中的数据源
                __weak typeof(self) weakSelf = self;
                if(self.updataDataSourceBlock){
                    NSString *count = [NSString stringWithFormat:@"%d%@%zd",weakSelf.currentPage+1,@" / ",weakSelf.dataSoure.count];
                    weakSelf.updataDataSourceBlock(weakSelf.dataSoure);
                    [[NSNotificationCenter defaultCenter]postNotificationName:@"scrollPage" object:count];
//                    [weakSelf.myCollectionView reloadData];
                }
                //首页进入加载完第一张图片马上再加载一批图片
                if(!weakSelf.entryFromStore&&!weakSelf.isNeedLoadMore){
                    weakSelf.isNeedLoadMore = YES;
                    if(weakSelf.loadMoreBlock){
                        weakSelf.loadMoreBlock();
                    }
                }
            }
        });
    }
}
- (NSString *)getTimeNow
{
    NSString* date;
    NSDateFormatter * formatter = [[NSDateFormatter alloc ] init];
    [formatter setDateFormat:@"YYYYMMddhhmmssSSS"];
    date = [formatter stringFromDate:[NSDate date]];
    //取出个随机数
    int last = arc4random() % 10000;
    NSString *timeNow = [[NSString alloc] initWithFormat:@"%@-%d", date,last];
    DLog(@"当前时间%@", timeNow);
    return timeNow;
}
- (void)_initSubviews{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    //每一行之间的最小距离
    layout.minimumLineSpacing = 0;
     //设置滑动方向
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    UICollectionView *collectionV = [[UICollectionView alloc]initWithFrame:self.bounds collectionViewLayout:layout];
    collectionV.showsHorizontalScrollIndicator = NO;
    //设置分页
    collectionV.pagingEnabled = YES;
    [self addSubview:collectionV];
    collectionV.backgroundColor = [UIColor blackColor];
    //设置代理
    collectionV.delegate = self;
    collectionV.dataSource = self;
    //注册
    [collectionV registerNib:[UINib nibWithNibName:@"ScanCollectionCell" bundle:nil] forCellWithReuseIdentifier:@"ScanCollectionCell"];
    _myCollectionView = collectionV;
    _myCollectionView.hidden = YES;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section;{
    return self.dataSoure.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath;{
    ScanCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ScanCollectionCell" forIndexPath:indexPath];
    QickScanModel *item = self.dataSoure[indexPath.row];
    cell.scanModel = item;
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
      return CGSizeMake(Main_Screen_Width, self.height);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    //点击图片进入入商品详情页
    QickScanModel *model = self.dataSoure[indexPath.row];
    GoodsDetailViewController *goodsDetail  = [[GoodsDetailViewController alloc]init];
    goodsDetail.pid = model.pid;
    goodsDetail.goodPic = model.pic;
        //count 用来区分进入快速浏览控制器的方式
    if(_count==1){//push进入
        goodsDetail.isNeedMessageItem = YES;

         [[self secondNavigationController] pushViewController:goodsDetail animated:YES];
    }
    if(_count==2){//模态弹出进入
        goodsDetail.isNeedMessageItem = NO;

        BaseNavigationViewController *navi = [[BaseNavigationViewController alloc]initWithRootViewController:goodsDetail];
        goodsDetail.isModel = YES;
        [[self baseViewController] presentViewController:navi animated:YES completion:nil];
    }
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
    //检测左测滑动,开始加载更多
    //如果不是店铺内快速浏览不需要执行以下代码
    if(!self.entryFromStore) return;
    //当没有图片或者没有偏移量的情况不执行以下代码
    if(scrollView.contentSize.width==0||scrollView.contentOffset.x==0) return;
    if(scrollView.contentOffset.x +scrollView.width - scrollView.contentSize.width >40){
//        DLog(@"scrollview.contentOffset.x-->%f,scrollview.width-->%f,scrollview.contentsize.width--%f",scrollView.contentOffset.x,scrollView.width,scrollView.contentSize.width);
        if (self.indicatorView == nil) {
            UIActivityIndicatorView *indicatorView = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(scrollView.width - 35, scrollView.top + scrollView.height/2 - 10, 35, 35)];
            indicatorView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
            indicatorView.hidesWhenStopped = YES;
            self.indicatorView = indicatorView;
            [self.indicatorView stopAnimating];
            [self addSubview:self.indicatorView];
        }
        if (!self.indicatorView.isAnimating) {
            scrollView.left = -40;
            [self.indicatorView startAnimating];
            if(self.loadMoreBlock){
                self.loadMoreBlock();
            }
        }
    }
}

//根据偏移量计算当前显示的页数 并将页数通知控制器显示
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
     int page = scrollView.contentOffset.x/Main_Screen_Width;
    DLog(@"偏移量----->%f-----当前页---%d",scrollView.contentOffset.x,page);
   
    if (page<=self.dataSoure.count-1){
    NSString *count = [NSString stringWithFormat:@"%d%@%zd",page+1,@" / ",self.dataSoure.count];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"scrollPage" object:count];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"currentPage" object:[NSString stringWithFormat:@"%d",page]];
    self.currentPage = page;
    }
}
- (BaseNavigationViewController*)secondNavigationController{
    UIResponder *next = self.nextResponder;
    while (next!=nil) {
        if([next isKindOfClass:[BaseNavigationViewController class]]){
            return (BaseNavigationViewController*)next;
        }
        next = next.nextResponder;
    }
    return nil;
}
- (BaseViewController*)baseViewController{
    UIResponder *next = self.nextResponder;
    while (next!=nil) {
        if([next isKindOfClass:[BaseViewController class]]){
            return (BaseViewController*)next;
        }
        next = next.nextResponder;
    }
    return nil;
}

@end
